package com.swmaestro.twar;

import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.swmaestro.twar.model.Feed;
import com.swmaestro.twar.model.FeedList;
import com.swmaestro.twar.task.URLs;

public class TimelineScreenActivity extends Activity {
	
	View iv_thumbnail_A;
	View iv_thumbnail_B;
	EditText et_feed;
	Button btn_submit;
	
	ListView list;
	LinearLayout empty;
//	Button btn_see_more;
	
	FeedAdapter mAdapter;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timeline_screen_layout);
        
        iv_thumbnail_A = (View)findViewById(R.id.iv_thumbnail_A);
        iv_thumbnail_B = (View)findViewById(R.id.iv_thumbnail_B);
        
        et_feed = (EditText)findViewById(R.id.et_feed);
        
        btn_submit = (Button)findViewById(R.id.btn_submit);        
        btn_submit.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
//				Toast.makeText(TimelineScreenActivity.this, et_feed.getText().toString(), Toast.LENGTH_SHORT).show();
				et_feed.setText("");
				
				mAdapter.insert(new Feed("Name", DateTime.now(), "Content", 1, 1, 1), 0);
				mAdapter.notifyDataSetChanged();
			}
        });
        
        list = (ListView)findViewById(R.id.list);
        /*
        empty = (LinearLayout)findViewById(R.id.empty);
        list.setEmptyView(empty);
        */

        mAdapter = new FeedAdapter(this, R.layout.feed_view_layout, new ArrayList<Feed>());
        list.setAdapter(mAdapter);
        
        list.setOnScrollListener(new EndlessScrollListener());
        /*
        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout footer_view = (LinearLayout)vi.inflate(R.layout.feed_list_footer_view_layout, null);
		list.addFooterView(footer_view);
		*/
        
    }
    
    ProgressDialog mProgressDialog;
    public void onResume() {
    		super.onResume();
    		
    		if(mAdapter.items.size() == 0) {
    			loadFeedList();
    		}
    		
    }
    
    int mLastFeedId = 0;
    public void loadFeedList() {
    		Toast.makeText(this, TimelineScreenActivity.this.mAdapter.items.size() + "", Toast.LENGTH_SHORT).show();
    		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.show();
		new FeedListDownloadTask().execute(mLastFeedId);
    }
    
    private class FeedAdapter extends ArrayAdapter<Feed> {

    		private ArrayList<Feed> items;

    		public FeedAdapter(Context context, int feedViewResourceId, ArrayList<Feed> items) {
    			super(context, feedViewResourceId, items);
    			this.items = items;
    		}
        
    		@Override
    		public View getView(int position, View convertView, ViewGroup parent) {
    			View v = convertView;
    			if (v == null) {
    				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    				v = vi.inflate(R.layout.feed_view_layout, null);
    			}
    			
    			Feed feed = this.items.get(position);
    			
    			if (feed != null) {
    				try{
    				TextView tv_name = (TextView)v.findViewById(R.id.tv_name);
    				TextView tv_date = (TextView)v.findViewById(R.id.tv_date);
    				TextView tv_content = (TextView)v.findViewById(R.id.tv_content);
    				TextView tv_num_of_ups = (TextView)v.findViewById(R.id.tv_num_of_ups);
    				TextView tv_num_of_downs = (TextView)v.findViewById(R.id.tv_num_of_downs);
    				
    				tv_name.setText(feed.name);
    				tv_date.setText(Utils.convertDateTime2String(feed.date, true));
    				tv_content.setText(feed.content);
    				tv_num_of_ups.setText(feed.num_of_ups + "");
    				tv_num_of_downs.setText(feed.num_of_downs + "");
    				
    				//test purpose
    				} catch(Exception e) {
    					e.printStackTrace();
    				}
    			} else {
//    				Log.e("test", "feed is NULL!!");
    			}
    			
    			return v;
    		}
    }
    
    private class FeedListDownloadTask extends AsyncTask<Integer, Void, FeedList> {
    		
		public static final String TASK_URL = URLs.URL_FEEDLIST;

		public String URL(Integer id) {
			//id
			StringBuilder url_sb = new StringBuilder();
			url_sb.append(TASK_URL);
			//append id
			
			return url_sb.toString();
		}
		
		protected FeedList doInBackground(Integer... params) {
			Integer id = params[0];
			String response = null;

			try {
	    			String url = URLs.URL_FEEDLIST;
	    			//url(id)
	    			//
	    			
//    			Log.d("test", "Server Request: " + url);	    			
	    			HttpClient client = new DefaultHttpClient();
	    			HttpGet get = new HttpGet(url);
	    			HttpResponse responseGet = client.execute(get);
	    			HttpEntity resEntityGet = responseGet.getEntity();
	    			if(resEntityGet != null) {
//    				response = new String(EntityUtils.toByteArray(resEntityGet), "utf-8");
	    	 			response = EntityUtils.toString(resEntityGet);
//	    				Log.e("test", "Server Response: " + response);
	    	            
	    	 			JSONArray ja = new JSONArray(response);
	    	 			FeedList feedList = new FeedList(ja);
//	    	 			FeedList.log("test", feedList);
	    	 			
	    	 			return feedList;
	    			} else {
	    				//?
	    			}
	    		} catch (JSONException e) {
	    			e.printStackTrace();
	    			//?
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    			//?
	    		}
			return null;
		}
		
		public void onPostExecute(FeedList feedList) {
			if(feedList != null) {
				for(int i=0; i<feedList.list.length; i++) {
					TimelineScreenActivity.this.mAdapter.add(feedList.list[i]);
//	 				TimelineScreenActivity.this.mLastFeedId++;
	 			}

				mAdapter.notifyDataSetChanged();
				
				//stop progress dialog
				if(TimelineScreenActivity.this.mProgressDialog != null) {
					TimelineScreenActivity.this.mProgressDialog.hide();
				}
				
	    			Toast.makeText(TimelineScreenActivity.this, TimelineScreenActivity.this.mAdapter.items.size() + "", Toast.LENGTH_SHORT).show();
			}
		}
    }
    
    public class EndlessScrollListener implements OnScrollListener {
    	
    		private int visibleThreshold = 5;
		private int currentPage = 0;
		private int previousTotal = 0;
		private boolean loading = true;
		
		public EndlessScrollListener() {
			
		}
		
		public EndlessScrollListener(int visibleThreshold) {
		this.visibleThreshold = visibleThreshold;
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			if (loading) {
				if (totalItemCount > previousTotal) {
					loading = false;
					previousTotal = totalItemCount;
					currentPage++;
				}
			}
			if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
				// I load the next page of gigs using a background task,
				// but you can call any function here.
				TimelineScreenActivity.this.loadFeedList();
				loading = true;
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}
	}
    

}